#include "AsyncDataSaver.h"
AsyncDataSaver::AsyncDataSaver(const char * path)
	: m_saving(true)
{
	//FILE* pfile = nullptr;
	fopen_s(&m_file, path, "wb");
	//for (size_t i = 0; i < 8; i++)
	//{
	//	char lpath[256];
	//	sprintf_s(lpath, "%s.ch%d.dat", path, i);
	//	FILE* pfile = nullptr;
	//	fopen_s(&pfile, lpath, "wb");
	//	m_files.push_back(pfile);
	//}
	m_pthread = new std::thread(&AsyncDataSaver::CoreSave,this);
}

AsyncDataSaver::~AsyncDataSaver()
{
	//for (auto file : m_files)
	//{
	//	fclose(file);
	//}
	fclose(m_file);
	delete m_pthread;
}

void AsyncDataSaver::Save(const char * pDst, const int dstLen)
{
	auto ptr = new char[dstLen];
	memcpy(ptr, pDst, dstLen);
	std::shared_ptr<char> sptr(ptr, [](char * ptr) {delete[] ptr; });
	auto tp = std::make_tuple(sptr, (int)dstLen);
	m_datas.push(tp);
}

void AsyncDataSaver::Finish()
{
	m_saving = false;
	m_pthread->join();
}

void AsyncDataSaver::CoreSave()
{
	while (m_saving)
	{
		auto data = m_datas.pop();
		auto dst = std::get<0>(data);
		auto len=std::get<1>(data);
		fwrite(dst.get(), len, 1, m_file);
		//unsigned short *pStart = (unsigned short *)dst.get();
		//auto pEnd = pStart + len / 2;
		//for (auto p= pStart; p < pEnd; p++)
		//{
		//	auto index = (*p) >> 12;
		//	fwrite(p, sizeof(unsigned short), 1, m_files[index]);
		//}
	}

}
